import json
import pandas as pd
import requests as rq
import copy
from coord_convert.transform import wgs2gcj, wgs2bd, gcj2wgs, gcj2bd, bd2wgs, bd2gcj
import time

def main():
    LL = []
    df = pd.read_excel('hubei4.xlsx', sheet_name='Sheet1', encoding='utf-8')
    print(df.columns)

    h = {'all':[]}
    # '急诊（心脑血管、外伤等重症）', '血液透析', '恶性肿瘤（含恶性\n血液病）','儿童（含新生儿）', '孕产妇'
    all = []
    for row in range(0, len(df)):
        d = df.iloc[row]
        print('\n\n\nNEWWWWWWWWWWWWWW---', row, len(df.iloc[row]))

        for i in range(0, len(d)):
            d[i] = str(d[i]).replace('\n',';').replace(' ',';')
        city = d[0].strip()
        emg = d[2].strip()
        emgTel = d[3].strip()
        all.append([city, emg, emgTel, ['emg']])

        dia = d[4].strip()
        diaTel = d[5].strip()
        all.append([city, dia, diaTel, ['dia']])

        tumor = d[6].strip()
        tumorTel = d[7].strip()
        all.append([city, tumor, tumorTel, ['tumor']])

        ped = d[8].strip()
        pedTel = d[9].strip()
        all.append([city, ped, pedTel, ['ped']])

        preg = d[10].strip()
        pregTel = d[11].strip()
        all.append([city, preg, pregTel, ['preg']])

    print(len(all))
    i = 0
    while i < len(all):
        # print(i)
        thisHospital = all[i]
        k = 0
        while k < len(all):
            if all[k][1] == all[i][1] and k != i:
                all[i][3].append(all[k][3][0])
                del all[k]
            else:
                k += 1
        i += 1

    print(len(all))
    h = []
    for item in all:
        time.sleep(0.1)
        if item[1] != '/' and item[1] != 'nan':
            print(item)
            h.append(parse(item))

        # if '（' in df.iloc[row, 1].split('\n')[0]:
        #
        #     name = df.iloc[row, 1].split('\n')[0][:df.iloc[row, 1].split('\n')[0].find('（')]
        # else:
        #     name = df.iloc[row, 1].split('\n')[0]
        # h['all'].append({
        #     'name': name,
        #     'city': str(df.iloc[row, 0]),
        #     'categ':[str(df.iloc[row, 3]) != 'nan', str(df.iloc[row, 4]) != 'nan', str(df.iloc[row, 5]) != 'nan',
        #              str(df.iloc[row, 6]) != 'nan', str(df.iloc[row, 7]) != 'nan'],
        #     'tel': str(df.iloc[row, 8]).replace('\n',';').replace(' ',''),
        #     'spec': str(df.iloc[row, 9]).replace('\n',';')
        # })

    # parse(h)
    out = {'all':h}
    with open('hubei2.json','w') as fw:
        fw.write(json.dumps(out, separators=(',',':'), ensure_ascii = False))

def parse(thisH):
    h = {}
    name = thisH[1]
    if thisH[0] == 'nan':
        city = ''
    else:
        city = thisH[0].replace(';','')

    url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
        '&keywords=' + name + '&types=090100|090200|090300|090400|090500&city=' + city + '&children=0&offset=1&page=1&extensions=all'
    response = rq.get(url)
    result = response.json()
    print(url)

    if len(result['pois']) != 0:
        for k, v in result['pois'][0].items():
            if v == []:
                result['pois'][0][k] = ''

        fmt_addr = result['pois'][0]['address']
        fmt_name = result['pois'][0]['name']
        fmt_type1 = result['pois'][0]['type'].split(';')[1]
        fmt_type2 = result['pois'][0]['type'].split(';')[2]
        fmt_alias = result['pois'][0]['alias'].replace('|', '；')
        fmt_district = result['pois'][0]['adname']
        fmt_lng = result['pois'][0]['location'].split(',')[0]
        fmt_lat = result['pois'][0]['location'].split(',')[1]
        fmt_tel = result['pois'][0]['tel']#.replace(';', '；')

        newLon, newLat = gcj2wgs(float(fmt_lng), float(fmt_lat))
        h['lng'] = round(newLon, 6)
        h['lat'] = round(newLat, 6)

        h['name_fmt'] = fmt_name
        h['addr'] = fmt_addr
        h['type1'] = fmt_type1
        h['type2'] = fmt_type2
        h['alias'] = fmt_alias
        h['city'] = result['pois'][0]['cityname']
        h['district'] = fmt_district
        h['tel'] = thisH[2]
        h['tel_gaode'] = fmt_tel

        thisCateg = []
        for dept in ['emg','dia','tumor','ped','preg']:
            if dept in thisH[3]:
                thisCateg.append(True)
            else:
                thisCateg.append(False)
        h['categ'] = thisCateg
        h['spec'] = ''
    else:
        h['addr'] = '404'
    return h
    # with open('hubei3.json','w') as fw:
    #     fw.write(json.dumps(h, separators=(',',':'), ensure_ascii=False))
if __name__ == '__main__':
    main()